package com.jvm.interpreter.instruction;

import com.jvm.classfile.model.CpInfo;
import com.jvm.interpreter.Frame;
import com.jvm.interpreter.Instruction;

/**
 * @program: diy_simple_jvm
 * @description: iinc指令
 * @author: CaoYong
 * @create: 2021-07-08 13:44
 **/
public class IIncInst implements Instruction {

    public final int index;
    public final int val;

    public IIncInst(int index, int val) {
        this.index = index;
        this.val = val;
    }

    @Override
    public int offset() {
        return 3;
    }

    /**
     * 将本地变量表指令参数1对应位置的值加上指令参数2，然后将结果放在本地变量表指令参数1位置
     * @param frame 栈帧
     */
    @Override
    public void eval(Frame frame) {
//        int tmp = frame.localVars.get(index);
        int tmp = frame.getInt(index);
        tmp += val;
//        frame.localVars.put(index, tmp);
        frame.setInt(index, tmp);
        frame.pc += offset();
    }

    static IIncInst parse(java.io.DataInputStream dis, CpInfo[] cp) throws java.io.IOException {
        return new IIncInst(dis.readUnsignedByte(), dis.readByte());
    }
}
